package com.paic.mhis.hcpms.agreement.protocol.util;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.paic.mhis.common.base.dto.BaseDTO;
import com.paic.mhis.common.base.dto.PaginatedQueryDTO;
import com.paic.mhis.common.base.intergration.dao.CommonDAO;
import com.paic.mhis.common.util.BusinessServiceUtil;
import com.paic.mhis.common.util.Constants;
import com.paic.mhis.common.validator.MapValidator;
import com.paic.mhis.common.validator.MapValueValidator;
import com.paic.mhis.hcpms.agreement.healthcareprovider.dto.HealthCareProviderDTO;
import com.paic.mhis.hcpms.agreement.protocol.biz.validator.AgreementValidator;
import com.paic.mhis.hcpms.agreement.protocol.dto.AgreementInfoDTO;
import com.paic.mhis.hcpms.agreement.protocol.dto.FileInfoDTO;
import com.paic.pafa.app.biz.service.BaseService;
import com.paic.pafa.app.biz.service.BusinessServiceException;
import com.pingan.um.client.exception.UMException;

@Component("agreementServiceUtil")
@Scope("prototype")
public class AgreementServiceUtil extends BaseService {

	private static final Logger logger = Logger
			.getLogger(AgreementServiceUtil.class);

	@Autowired
	private CommonDAO commonDao;

	private AgreementValidator validator;

	public Map<String, Object> add(JSONObject transferJson, String currentUser)
			throws BusinessServiceException {
		AgreementInfoDTO infoDTO = null;
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			infoDTO = JSONObject.toJavaObject(transferJson,
					AgreementInfoDTO.class);
			validator = (AgreementValidator) context
					.getBean("agreementValidator");
			// dateValidator(infoDTO);

			// Map<Object, Object> validateResult =
			// validator.validate(fieldMap);

			String id = commonDao.getUUID();
			infoDTO.setId(id);
			// 协议编号
			infoDTO.setIsValid(AgreementConstants.IS_VALID_TRUE);

			this.commonDao.insert(AgreementSqlMapIdConstants.AGREEMENT_INSERT,
					infoDTO);
			result.put(Constants.SUCCESS_RESULT_KEY, id);
			generateSuccessResult(result, Constants.SUCCESS_STATE_VALUE,
					AgreementConstants.ADD_AGREEMENT_INFO_SUCCESS);
		} catch (Exception e) {
			BusinessServiceUtil.processException(e);
		}
		return result;
	}

	public Map<String, Object> addImage(JSONObject transferJson,
			String currentUser, String fileName, long fileSize)
			throws BusinessServiceException {
		FileInfoDTO infoDTO = null;
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			infoDTO = JSONObject.toJavaObject(transferJson, FileInfoDTO.class);
			String id = commonDao.getUUID();
			double file_Msize = fileSize / (1024.0 * 1024.0);
			BigDecimal file_MsizeTemp = new BigDecimal(file_Msize);
			file_Msize = file_MsizeTemp.setScale(2, BigDecimal.ROUND_HALF_UP)
					.doubleValue();
			infoDTO.setImageIndex(id);
			infoDTO.setIsValid(AgreementConstants.IS_VALID_TRUE);
			infoDTO.setImageStatus("0");
			infoDTO.setImageType("02");
			infoDTO.setBusinessNo(infoDTO.getId());
			infoDTO.setImageName(fileName);
			infoDTO.setFileSize(String.valueOf(file_Msize) + "M");
			this.commonDao.insert(AgreementSqlMapIdConstants.IMAGEINFO_INSERT,
					infoDTO);
			generateSuccessResult(result, Constants.SUCCESS_STATE_VALUE,
					AgreementConstants.ADD_IMAGE_INFO_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			BusinessServiceUtil.processException(e);
		}
		return result;
	}

	public Map<String, Object> update(JSONObject transferJson,
			String currentUser) throws BusinessServiceException {
		AgreementInfoDTO infoDTO = null;
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> param = new HashMap<String, Object>();

		try {
			Map<Object, Object> fieldMap = JSONObject.toJavaObject(
					transferJson, Map.class);
			infoDTO = JSONObject.toJavaObject(transferJson,
					AgreementInfoDTO.class);
			infoDTO.setUpdatedBy(currentUser);
			validator = (AgreementValidator) context
					.getBean("agreementValidator");
			// dateValidator(infoDTO);
			// Map<Object, Object> validateResult =
			// validator.validate(fieldMap);

			infoDTO.setIsValid(AgreementConstants.IS_VALID_TRUE);
			this.commonDao.update(AgreementSqlMapIdConstants.AGREEMENT_UPDATE,
					infoDTO);
			generateSuccessResult(result, Constants.SUCCESS_STATE_VALUE,
					AgreementConstants.UPDATE_AGREEMENT_INFO_SUCCESS);

		} catch (Exception e) {
			BusinessServiceUtil.processException(e);
		}
		return result;
	}

	public Map<String, Object> queryPage(int pageSize, int page,
			Map<String, Object> params) throws BusinessServiceException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {

			PaginatedQueryDTO dto = new PaginatedQueryDTO();
			dto.setStart(pageSize);
			dto.setLimit(page);
			dto.setParam(params);
			return commonDao.queryPage(
					AgreementSqlMapIdConstants.AGREEMENT_QUERYPAGE, dto);
		} catch (Exception e) {
			// BusinessServiceUtil.processException(e);
			e.printStackTrace();
		}
		return resultMap;
	}

	public Map<String, Object> get(String id) throws BusinessServiceException {
		Map<String, Object> infoDTO;
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		try {
			// 服务协议类型
			paramsMap.put("id", id);
			infoDTO = (Map<String, Object>) commonDao.get(
					AgreementSqlMapIdConstants.AGREEMENT_GET_BY_NO, paramsMap);
			if (null == infoDTO || infoDTO.size() == 0) {
				generateSuccessResult(result, Constants.FAILED_STATE_VALUE,
						"该协议已被其他用户删除，请核实");
				return result;
			}
			result.put(Constants.SUCCESS_RESULT_KEY, infoDTO);
			generateSuccessResult(result, Constants.SUCCESS_STATE_VALUE,
					Constants.SELECT_SUCCESS);
		} catch (Exception e) {
			BusinessServiceUtil.processException(e);
		}
		return result;
	}

	public Map<String, Object> getImage(String id)
			throws BusinessServiceException {
		Map<String, Object> infoDTO = new HashMap<String, Object>();
		Map<String, Object> result = new HashMap<String, Object>();
		List imgList = null;
		try {
			imgList = commonDao.query("healthcare.queryImgList", id);
			infoDTO.put("imgList", imgList);
			result.put(Constants.SUCCESS_RESULT_KEY, infoDTO);
			generateSuccessResult(result, Constants.SUCCESS_STATE_VALUE,
					Constants.SELECT_SUCCESS);
		} catch (Exception e) {
			BusinessServiceUtil.processException(e);
		}
		return result;
	}

	private void generateSuccessResult(Map<String, Object> result,
			String stateValue, String msgValue) {
		result.put(Constants.STATE_KEY, stateValue);
		result.put(Constants.MSG_KEY, msgValue);
	}

	public void dateValidator(final AgreementInfoDTO agreementInfoDTO) {
		MapValidator mapValidator = new MapValueValidator("",
				"同一医疗机构、同一服务类型的协议，生效、终止时间不能交叉", "") {
			boolean f;

			AgreementInfoDTO tmp = agreementInfoDTO;

			@Override
			protected boolean validateSuccess(Object value) {
				try {
					f = getdateValidator(tmp);
				} catch (BusinessServiceException e) {
					e.printStackTrace();
				}
				return f;
			}
		};

		validator.addList(mapValidator);
	}

	public Boolean getdateValidator(AgreementInfoDTO agreementInfoDTO)
			throws BusinessServiceException {
		Map<String, Object> infoDTO = null;
		Map<String, Object> param = new HashMap<String, Object>();
		boolean f = true;
		try {
			param.put("agreementType", agreementInfoDTO.getAgreementType());
			param.put("idHealthcareProvider",
					agreementInfoDTO.getIdHealthcareProvider());
			param.put("dateAgreementEff",
					agreementInfoDTO.getDateAgreementEff());
			param.put("dateAgreementEnd",
					agreementInfoDTO.getDateAgreementEnd());
			param.put("id", agreementInfoDTO.getId());

			infoDTO = (Map<String, Object>) this.commonDao.get(
					AgreementSqlMapIdConstants.AGREEMENT_DATE_COUNT, param);
			if (Integer.valueOf(infoDTO.get("agreementDatecount").toString()) > 0) {
				f = false;
			}
		} catch (Exception e) {
			BusinessServiceUtil.processException(e);
		}
		return f;
	}

	private Map<String, Object> checkAgreementInfo(AgreementInfoDTO infoDTO,
			String currentUser) throws UMException {
		HealthCareProviderDTO healthCareProviderDTO;
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> param = new HashMap<String, Object>();
		Map<String, Object> tempParam = new HashMap<String, Object>();
		List<BaseDTO> list = null;
		param.put("idHealthcareProvider", infoDTO.getIdHealthcareProvider());
		healthCareProviderDTO = (HealthCareProviderDTO) this.commonDao.get(
				"healthcare.getorgType", param);
		if (null == healthCareProviderDTO) {
			generateSuccessResult(result, Constants.FAILED_STATE_VALUE,
					"服务机构id不存在!");
			return result;
		}
		String codetype = AgreementConstants.AGREEMENTTYPE;
		tempParam.put("codeType", codetype);
		tempParam.put("codeNo", infoDTO.getAgreementType());

		list = commonDao.query("base.codeTypes", tempParam);
		if (list.size() == 0) {
			generateSuccessResult(result, Constants.FAILED_STATE_VALUE,
					"协议类型不存在!");
			return result;
		}
		list = null;
		tempParam = new HashMap<String, Object>();
		codetype = AgreementConstants.PAYMENTMODE;
		String payMode = infoDTO.getPayMentMode();
		tempParam.put("codeType", codetype);
		String[] payModes = payMode.split(",");
		for (int i = 0; i < payModes.length; i++) {
			tempParam.put("codeNo", payModes[i]);
			list = commonDao.query("base.codeTypes", tempParam);
			if (list.size() == 0) {
				generateSuccessResult(result, Constants.FAILED_STATE_VALUE,
						"支付方式不存在!");
				return result;
			}
		}
		// 获取统筹区域
		List<String> area;
		// area = um2Service.getPrincipalsRegionByID(currentUser);
		// if (!area.contains(infoDTO.getRegionCode())) {
		// generateSuccessResult(result, Constants.FAILED_STATE_VALUE,
		// "该统筹区域不属于当前用户!");
		// return result;
		// }
		return result;
	}

}
